﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using System.Web.Security;
using System.Configuration;

namespace TireService.Web.UserControls
{
    public partial class upEditCustomerSubscription : System.Web.UI.UserControl
    {
        private string _controlname = "EditCustomerSubscription";

        //public int CustomerId
        //{
        //    get
        //    {
        //        if (ViewState["_customerid"] != null)
        //            return (int)ViewState["_customerid"];
        //        else
        //            return 0;
        //    }
        //    set
        //    {
        //        ViewState["_customerid"] = value;
        //    }
        //}

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToBoolean(Session["UserControlLoaded" + _controlname]))
            {
                // Initiate datalayer
                TireServiceDB db = new TireServiceDB();

                // Show customer subscriptions
                LoadCustomerSubscription(Convert.ToInt32(Session["CustomerId" + _controlname]), db);
            }            
        }

        protected void callbackEditCustomerSubscriptionPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            Session["CustomerId" + _controlname] = Convert.ToInt32(e.Parameter);

            LoadUserControl(Convert.ToInt32(e.Parameter));
        }

        /// <summary>
        /// Public function for loading usercontrol
        /// </summary>
        public void LoadUserControl(int CustomerId)
        {
            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            if (CustomerId != 0)
            {
                // Show customer subscriptions
                LoadCustomerSubscription(CustomerId, db);
            }
            else
            {
                // Error
                throw new ArgumentException("Kunde ikke fundet");
            }

            // Dispose connection to database
            db.Dispose();
        }

        public void LoadCustomerSubscription(int CustomerId, TireServiceDB db) 
        {
            Session["CustomerId" + _controlname] = CustomerId;
            
            //List<CustomerSubscriptionView> customersubscription = db.GetCustomerSubscriptionViews(CustomerId); // NOTE: Ændret d. 22/9-2012
            List<BusinessSubscriptionListView> customersubscription = db.GetCustomerBusinessSubscriptions(CustomerId, cbShowChildCustomerSubscriptions.Checked);

            // Bind to gridview
            gvCustomerSubscription.DataSource = customersubscription;
            gvCustomerSubscription.DataBind();

            // Prepare data for editmode of customer subscription
            GridViewDataComboBoxColumn ddlSubscription = gvCustomerSubscription.Columns["SubscriptionDropdown"] as GridViewDataComboBoxColumn;
            ddlSubscription.PropertiesComboBox.ValueType = typeof(int);
            ddlSubscription.PropertiesComboBox.DataSource = db.GetSubscription();
            ddlSubscription.PropertiesComboBox.TextField = "Description";
            ddlSubscription.PropertiesComboBox.ValueField = "SubscriptionId";
            ddlSubscription.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlSubscription.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            Session["UserControlLoaded" + _controlname] = true;
        }

        /// <summary>
        /// Postback function that binds customer subscription gridview
        /// </summary>
        protected void gvCustomerSubscription_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            LoadCustomerSubscription(Convert.ToInt32(Session["CustomerId" + _controlname]), db);
        }

        /// <summary>
        /// Gridview function for updating customer subscription
        /// </summary>
        protected void gvCustomerSubscription_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            if (Convert.ToInt32(Session["CustomerId" + _controlname]) != 0)
            {
                TireServiceDB db = new TireServiceDB();

                // Get id
                int CustomerSubscriptionId = Convert.ToInt32(e.Keys["CustomerSubscriptionId"]);

                CustomerSubscription customersubscription = new CustomerSubscription();

                // Fetch customer
                Customer customer = db.GetCustomer(Convert.ToInt32(Session["CustomerId" + _controlname]));

                Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Create customer subscription
                CustomerSubscriptionBLL customersubscriptionBLL = new CustomerSubscriptionBLL();
                customersubscriptionBLL.UpdateCustomerSubscription(
                    db,
                    customersubscription,
                    customer,
                    CustomerSubscriptionId,
                    Convert.ToInt32(e.NewValues["SubscriptionId"]),
                    Convert.ToDateTime(e.NewValues["LastRenewalDate"]),
                    Convert.ToDateTime(e.NewValues["NextRenewalDate"]),
                    Convert.ToBoolean(e.NewValues["InActive"]),
                    Convert.ToBoolean(e.NewValues["BalancingIncluded"]),
                    Convert.ToDecimal(e.NewValues["Price"]),
                    userid,
                    false,
                    "Redigering af abonnement"
                );

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvCustomerSubscription.CancelEdit();

                // Refresh gridview
                LoadCustomerSubscription(Convert.ToInt32(Session["CustomerId" + _controlname]), db);

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new InvalidOperationException("Kunde data ikke gemt endnu - kunde abonnement kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }

        /// <summary>
        /// Gridview function for creating customer subscription
        /// </summary>
        protected void gvCustomerSubscription_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {

            if (Convert.ToInt32(Session["CustomerId" + _controlname]) != 0)
            {
                TireServiceDB db = new TireServiceDB();

                // Reset id
                int CustomerSubscriptionId = 0;

                CustomerSubscription customersubscription = new CustomerSubscription();

                // Fetch customer
                Customer customer = db.GetCustomer(Convert.ToInt32(Session["CustomerId" + _controlname]));

                Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Create customer subscription
                CustomerSubscriptionBLL customersubscriptionBLL = new CustomerSubscriptionBLL();
                customersubscriptionBLL.UpdateCustomerSubscription(
                    db,
                    customersubscription,
                    customer,
                    CustomerSubscriptionId,
                    Convert.ToInt32(e.NewValues["SubscriptionId"]),
                    Convert.ToDateTime(e.NewValues["LastRenewalDate"]),
                    Convert.ToDateTime(e.NewValues["NextRenewalDate"]),
                    Convert.ToBoolean(e.NewValues["InActive"]),
                    Convert.ToBoolean(e.NewValues["BalancingIncluded"]),
                    Convert.ToDecimal(e.NewValues["Price"]),
                    userid,
                    false,
                    "Oprettelse af abonnement"
                );

                // Check if invoice needs to be created
                ASPxCheckBox cbGenerateInvoice = (ASPxCheckBox)gvCustomerSubscription.FindEditFormTemplateControl("cbGenerateInvoice");
                ASPxCheckBox cbEmailInvoice = (ASPxCheckBox)gvCustomerSubscription.FindEditFormTemplateControl("cbEmailInvoice");

                // Create invoice selected
                if (cbGenerateInvoice.Checked)
                {
                    //int customerid_invoiced = customer.CustomerId;

                    //// Check if invoice is paid by parent customer
                    //if (customer.ParentPayInvoice & customer.ParentCustomerId != null)
                    //{
                    //    customerid_invoiced = Convert.ToInt32(customer.ParentCustomerId);
                    //}

                    // Get Customer Id on invoice payment responsible
                    CustomerBLL customerBLL = new CustomerBLL();
                    int PayingCustomerId = customerBLL.GetPayingCustomerId(db, customer.CustomerId);

                    // Initiate Economic interface
                    EconomicInterface ecoInterface = new EconomicInterface();

                    // Create subscription invoice in E-conomic
                    string invoiceid = ecoInterface.CreateSubscriptionInvoice(db, PayingCustomerId, customersubscription, customersubscription.Price);

                    if (cbEmailInvoice.Checked)
                    {
                        EmailNotificationServices emailService = new EmailNotificationServices();

                        string email = customer.Email;
                        string name = customer.Name;

                        if (PayingCustomerId != customer.CustomerId)
                        {
                            Customer PayingCustomer = db.GetCustomer(PayingCustomerId);

                            email = PayingCustomer.Email;
                            name = PayingCustomer.Name;
                        }

                        emailService.SubscriptionRenewal_SendCustomerInvoice(PayingCustomerId, email, name, customersubscription.CustomerId.ToString() + "-" + customersubscription.SubscriptionId.ToString() + "-" + customersubscription.CustomerSubscriptionId.ToString(), invoiceid, ecoInterface.GetInvoice(Convert.ToInt32(invoiceid)), "Faktura" + invoiceid + ".pdf", Shared.PaymentGateWayActions.InitiatePayment.ToString(), Convert.ToString(ConfigurationManager.AppSettings["AcceptURL"]));
                        // TODO: Evaluate if email function is correct - ex. if PFA then it should not send an email, but maybe to our finance mail to inform about it?
                    }

                }

                // Commit changes to database
                db.SubmitChanges();

                // End edit mode
                e.Cancel = true;
                gvCustomerSubscription.CancelEdit();

                // Refresh gridview
                LoadCustomerSubscription(Convert.ToInt32(Session["CustomerId" + _controlname]), db);

                // Close db connection
                db.Dispose();
            }
            else
            {
                // Customer not yet saved
                throw new InvalidOperationException("Kunde data ikke gemt endnu - kunde abonnement kan derfor ikke oprettes. Venligst gem kundedata først.");
            }
        }
    }
}